<template>
    <span @click="() => { if (disabled) return; show = true }">{{ text || placeholder || '请选择' }}</span>
    <Popup :show="show" position="bottom" @click-overlay="close">
        <Cascader v-model="checked" :options="options" :fieldNames="columnsFieldNames" @finish="onFinish"
            @close="onClose">
        </Cascader>
    </Popup>
</template>
<script setup lang="ts">
import { Utils } from "@b/model/base/utils";
import { Cascader, Popup } from "vant";
import type { CascaderOption, CascaderFieldNames } from "vant";
import { ref, watch, computed } from "vue";

interface prop {
    value?: number | string
    overlayClose?: boolean
    options: CascaderOption[]
    placeholder?: string
    columnsFieldNames?: CascaderFieldNames
    disabled?: boolean
}
const { value = '', options, placeholder, columnsFieldNames = { text: 'text', value: 'value', children: 'children' }, disabled, overlayClose = true } = defineProps<prop>()
const checked = ref(value)
const emits = defineEmits(['confirm'])
const show = ref(false)
const text = ref('')

const textLabel = computed(() => columnsFieldNames?.text || 'text')
const valueLabel = computed(() => columnsFieldNames?.value || 'value')
const childrenLabel = computed(() => columnsFieldNames?.children || 'children')

watch(() => value, (val) => {
    checked.value = val
    Utils.deepForeach(options, (item, parent, parents) => {
        if (item[valueLabel.value] === val) {
            text.value = parents.map(item => item[textLabel.value]).join('/')
        }
    }, {
        child: childrenLabel.value
    })
}, {
    immediate: true
})

const close = () => {
    if (overlayClose) show.value = false
}
const onFinish = ({ value, selectedOptions }: { value: string | number, selectedOptions: CascaderOption[] }) => {
    text.value = selectedOptions.map(item => item[textLabel.value]).join('/')
    emits('confirm', value)
    show.value = false
}
const onClose = () => {
    show.value = false
}
</script>
